package http_servicer

import (
	"fmt"
	"ifms/db_servicer"
	"net"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"time"
)

//var tcp_conn net.Conn
var remotePort string = os.Getenv("TPRT") // "9721"
var chan2Device chan string

func GetIP(req *http.Request) (string, int32, error) {
	var p int
	// logger = log.New(os.Stdout, "GetIP :", log.LstdFlags|log.Lshortfile)

	ip, port, err := net.SplitHostPort(req.RemoteAddr)

	if err != nil {
		//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
		logger.Printf("userip: %q is not IP:port", req.RemoteAddr)
		return "", 0, err
	}

	userIP := net.ParseIP(ip)
	if userIP == nil {
		//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
		logger.Printf("userip: %q is not IP:port", req.RemoteAddr)
		return "", 0, err
	}

	// This will only be defined when site is accessed via non-anonymous proxy
	// and takes precedence over RemoteAddr
	// Header.Get is case-insensitive
	forward := req.Header.Get("X-Forwarded-For")
	p, err = strconv.Atoi(port)
	if err != nil {
		p = 0
	}
	if forward != "" {
		return forward, int32(p), nil
	} else {

		return userIP.String(), int32(p), nil
	}

}

//Trigger TCP_SVR to send data back to all device belongs to the user
func sendAlertNum2Device(p_user_id int) {
	for _, p := range db_servicer.DevicesList4User(p_user_id) {

		//	send2Device(p)
		chan2Device <- p
	}

}

//this function will trigger the TCP_SVR to send data back to device
// by send a time sync data frame to the TCP_SVR
func send2Device() {
	// logger = log.New(os.Stdout, "Send data to Device :", log.LstdFlags|log.Lshortfile)

	// if tcp_conn == nil {

	//	logger.Printf("Dailing to local tcp port: %v .....", remotePort)

	for {

		device_id, ok := <-chan2Device
		if ok {

			conn, err := net.Dial("tcp", "localhost"+remotePort)
			if err != nil {
				logger.Printf(">>Error while Dailing TCP:%v\n", err)
			}
			logger.Printf("Dailed to TCP Svr at localhost:%v, get [%T]:%v\n", remotePort, conn, conn)
			dataStr := fmt.Sprintf("@;%v;6;0;", device_id)

			logger.Printf(`Data to be sent:"%v" ===> [%v] \n`, dataStr, device_id)

			fmt.Fprintf(conn, "%s\n", dataStr) /// heart beating data frame

			<-time.After(120 * time.Millisecond)
			if conn != nil {
				conn.Close()
			}

		}

	}

}

func ValidDateFormat(d string) bool {

	if regexp.MustCompile(`^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$`).MatchString(d) {

		return true
	} else {
		return false
	}

}

// func Version() string {
// 	return version
// }

func SetVersiton(v string) {
	version = v
}
